<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2018/3/12
 * Time: 10:38
 */

namespace org\util\forensictool\forensicreport;

use org\util\wordtool\Table;
use org\util\forensictool\ForensicCalculate;
use org\util\forensictool\LittleTools;
use org\util\wordtool\Word;
use think\Exception;

class ReportTy extends BaseReport
{
    /**
     * @throws \Exception
     */
    public function makeReport()
    {
        $this->makeFob();
        parent::makeReport();
    }

    /**
     * @throws \Exception
     */
    protected function makeSampleTable()
    {
        $tempPage=Word::instance()->createTemp();
        $table = $tempPage->addTable(self::TABLE_STYLE);
        $roleGroup = $this->makeRoleGroup();
        foreach ($roleGroup[1] as $role) {
            $this->addRow($table, $role);
        }
        foreach ($roleGroup[0] as $index => $role) {
            $position = $index == count($roleGroup[0]) - 1 ? 'last' : 'mid';
            $this->addRow($table, $role, $position);
        }
        return $tempPage;
    }

    /**
     * @param Table $table
     * @param string $role
     * @param string $position
     * @throws \Exception
     */
    protected function addRow(Table $table, $role, $position = 'mid')
    {
        $positionMap = ['first' => self::FIRST_ROW_STYLE, 'mid' => self::MID_ROW_STYLE, 'last' => self::LAST_ROW_STYLE];
        $width = [4000, 4000];
        if ($role == 'head') {
            $content = ['检材描述', '样本编号'];
        } else {
            $content = [$this->caseData['samples'][$role]['person_name'], $this->caseData['samples'][$role]['sample_name']];
        }
        $table->addSimpleRow($content, $width, self::TABLE_FONT, $positionMap[$position]);
    }

    /**
     * @throws \Exception
     */
    protected function makeDetectionTable()
    {
        $roleGroup = $this->makeRoleGroup();
        $tempPage=Word::instance()->createTemp();
        //设置单元格宽度
        $positionMap = ['first' => self::FIRST_ROW_STYLE, 'mid' => self::MID_ROW_STYLE, 'last' => self::LAST_ROW_STYLE];
        $width = 8000 / (count($roleGroup[1]) + 1);

        //每个亲代与每个子代生成对比表格
        $tableIndex = 0;
        foreach ($roleGroup[0] as $yz) {

            $tableIndex++;
            $arrMarker = [];//全部基因座
            $nameWz='';//未知样编号串
            $head = ['基因座'];//第一行

            foreach ($roleGroup[1] as $wz) {
                $arrMarker = array_merge($arrMarker, array_keys($this->caseData['samples'][$yz]['genotype']));
                $head[] = $this->caseData['samples'][$wz]['sample_name'];
                $nameWz.=$this->caseData['samples'][$wz]['sample_name'].'、';
            }
            $head[]=$this->caseData['samples'][$yz]['sample_name'];
            $nameWz=mb_substr($nameWz,0,-1);

            $tableDes='表'.$tableIndex.'：'.$nameWz.'和'.$this->caseData['samples'][$yz]['sample_name'].'号检材STR基因座的基因分型结果';//表头
            $tempPage->addPr($tableDes,self::TABLE_DES_FONT,self::TEXT_TAB+['spaceAfter'=>30,'spaceBefore'=>30]);

            $table = $tempPage->addTable(self::TABLE_STYLE);
            foreach ($arrMarker as $marker) {
                $content=[$marker];
                foreach ($roleGroup[1] as $wz) {
                    $content[]=$this->caseData['samples'][$wz]['genotype'][$marker];
                }
                $content[]=$this->caseData['samples'][$yz]['genotype'][$marker];
                $position = $marker == end($arrMarker) ? 'last' : 'mid';
                $table->addSimpleRow($content, $width, self::TABLE_FONT, $positionMap[$position]);
            }
        }
        return $tempPage;
    }


    /**
     * @throws \Exception
     */
    public function makeRecord()
    {
        $rep = parent::makeRecord();

        $roleGroup = $this->makeRoleGroup();
        $tempPage=Word::instance()->createTemp();
        //设置单元格宽度
        $positionMap = ['first' => self::FIRST_ROW_STYLE, 'mid' => self::MID_ROW_STYLE, 'last' => self::LAST_ROW_STYLE];
        $width = 8000 / (count($roleGroup[1]) + 1);

        //每个亲代与每个子代生成对比表格
        $tableIndex = 0;
        foreach ($roleGroup[0] as $yz) {

            $tableIndex++;
            $arrMarker = [];//全部基因座
            $nameWz='';//未知样编号串
            $head = ['基因座'];//第一行

            foreach ($roleGroup[1] as $wz) {
                $arrMarker = array_merge($arrMarker, array_keys($this->caseData['samples'][$yz]['genotype']));
                $head[] = $this->caseData['samples'][$wz]['sample_name'];
                $nameWz.=$this->caseData['samples'][$wz]['sample_name'].'、';
            }
            $head[]=$this->caseData['samples'][$yz]['sample_name'];

            $table = $tempPage->addTable(self::TABLE_STYLE);
            foreach ($arrMarker as $marker) {
                $content=[$marker];
                foreach ($roleGroup[1] as $wz) {
                    $content[]=$this->caseData['samples'][$wz]['genotype'][$marker];
                }
                $content[]=$this->caseData['samples'][$yz]['genotype'][$marker];
                $position = $marker == end($arrMarker) ? 'last' : 'mid';
                $table->addSimpleRow($content, $width, self::TABLE_FONT, $positionMap[$position]);
            }
        }
        $rep['CAL_TABLE']=$tempPage;
        $reportTemplate = $_SERVER['DOCUMENT_ROOT'].'/template/forensic/record.docx';
        $reportSavePath = $_SERVER['DOCUMENT_ROOT'].'/report/forensic/'.$this->caseData['case_id']. iconv('UTF-8','GB2312//IGNORE','-检验记录表.docx') ;
        Word::instance()->setTemplate($rep,$reportTemplate,$reportSavePath);
    }

    /**
     * @throws \Exception
     */
    //生成DNA部分分析说明
    protected function makeDescribe()
    {
        $describeDom=Word::instance()->createTemp();//分析部分
        $concludeDom=Word::instance()->createTemp();//结论部分
        $roleGroup = $this->makeRoleGroup();//角色表
        $arr_marker=array_keys($this->caseData['samples'][$roleGroup[0][0]]['genotype']);//TODO
        $markerNum = count($arr_marker);//基因座数量
        $strNum = $markerNum - 1;
        $describeDom->addPr($arr_marker[0] . '等' . $strNum . '个STR基因座均为人类遗传学标记，联合应用可进行个体识别，其累积个体识别能力大于0.9999。',self::BODY_FONT,self::TEXT_TAB);
        $concludeDom->addText('依据现有资料和DNA检验结果,',self::BODY_FONT,self::TEXT_TAB);
        $conclude='';
        foreach ($roleGroup[0] as $yz) {//每个已知样
            $yzName = $this->caseData['samples'][$yz]['person_name'];//姓名

            foreach ($roleGroup[1] as $wz) {//每个未知样
                $wzName=$this->caseData['samples'][$wz]['person_name'];//姓名

                $calResult=ForensicCalculate::instance()
                    ->setCaseType($this->caseData['case_type'])
                    ->setGenotypeF($this->caseData['samples'][$wz]['genotype'])
                    ->setGenotypeC($this->caseData['samples'][$yz]['genotype'])
                    ->setFrequency($this->frequency)
                    ->calculate();//计算并获取结果

                $strFailMarker = null;
                $failMarker=[];
                $failCount = 0;
                $CPI_data=1;
                foreach ($calResult as $marker=>$result) {
                    if (isset($result[2]) && $result[2]=='不匹配'){//不匹配项汇总
                        $failMarker[]=$marker;
                        $strFailMarker.=$marker.'、';
                        $failCount++;
                    }
                    if(isset($result[0])){//计算CPI
                        $CPI_data*=$result[0];
                    }
                }

                $arr_CPI = LittleTools::ciFang($CPI_data);
                $strFailMarker=mb_substr($strFailMarker,0,-1);

                if ($CPI_data == 0) {//否定结论
                    $describe = '经常染色体STR检测，在上述' . $strNum . '个STR基因座中的'.$strFailMarker.'等'.$failCount.'个基因座，'.$wzName.'的STR分型与'.$yzName.'的STR分型不同。';
                    $conclude .= '排除'.$wzName.'与'.$yzName.'来源于同一个体；';
                } else{
                    $describe = '经常染色体STR检测，在'.$arr_marker[0] . '等' . $strNum . '个STR基因座，'.$wzName.'的STR分型与'.$yzName.'的STR分型均相同，经计算，似然率为'.$arr_CPI[0].'。';
                    $conclude .= '支持'.$wzName.'与'.$yzName.'来源于同一个体；';
                }
                $describeDom->addPr($describe,self::BODY_FONT,self::TEXT_TAB)
                    ->addText($CPI_data < 10000 ? '' : '×10',self::BODY_FONT)
                    ->addText($CPI_data < 10000 ? '' : $arr_CPI[1],self::BODY_FONT+['super'=>true])
                    ->addText('。',self::BODY_FONT);
            }
        }

        $conclude = mb_substr($conclude, 0,-1);
        $conclude .= '。';
        $concludeDom->addText($conclude,self::BODY_FONT,self::TEXT_TAB);
        $this->describe=$describeDom;
        $this->conclude=$concludeDom;
    }

    /**
     * @throws \Exception
     */
    protected function makeFob()
    {
        $arrFob=[];
        $arrPos=[];
        $arrNeg=[];
        foreach ($this->caseData['samples'] as $role=>$sample) {
            switch ($sample['sample_fob']){
                case 1:
                    $arrFob[]=$role;
                    $arrPos[]=$role;
                    break;
                case 2:
                    $arrFob[]=$role;
                    $arrNeg[]=$role;
                    break;
            }
       }

        $actFob='';
        $actPos='';
        $actNeg='';
        $desPos='';
        $desNeg='';
        foreach ($arrFob as $item) {
            $actFob.= $this->caseData['samples'][$item]['sample_name'].'、';
        }
        foreach (
            $arrPos as $item) {$actPos.= $this->caseData['samples'][$item]['sample_name'].'、';
            $desPos.= $this->caseData['samples'][$item]['person_name'].'、';
        }
        foreach ($arrNeg as $item) {
            $actNeg.= $this->caseData['samples'][$item]['sample_name'].'、';
            $desNeg.= $this->caseData['samples'][$item]['person_name'].'、';
        }
        $actFob=mb_substr($actFob,0,-1);
        $actPos=mb_substr($actPos,0,-1);
        $actNeg=mb_substr($actNeg,0,-1);
        $desPos=mb_substr($desPos,0,-1);
        $desNeg=mb_substr($desNeg,0,-1);

        //阳性样本
        if(count($arrPos)>0){
            $str_pos_spid=$actPos.'呈阳性';
            $str_pos_describe=$desPos.'呈阳性，提示其为人血；';
            $str_pos_conclude=$desPos.'为人血；';
        }else{
            $str_pos_spid='';
            $str_pos_describe='';
            $str_pos_conclude='';
        }

        //阴性样本  /n
        if(count($arrNeg)>0){
            $str_neg_spid='，'.$actNeg.'呈阴性';
            $str_neg_describe='，'.$desNeg.'呈阴性，提示其不是人血；';
            $str_neg_conclude='，'.$desNeg.'不是人血；';
        }else{
            $str_neg_spid='';
            $str_neg_describe='';
            $str_neg_conclude='';
        }

        //完成描述
        if(count($arrFob)>0){
            $str['spn']='按照GA/T 383-2014《法庭科学DNA实验室检验规范》，使用抗人血红蛋白金标试纸条检测'.$actFob.'，结果'.$str_pos_spid.$str_neg_spid.'（见附件）。';
            $str['describe']='经人血斑确证试验，'.$str_pos_describe.$str_neg_describe;
            $str['conclude']=$str_pos_conclude.$str_neg_conclude;
        }else{
            $str['spn']='';
            $str['describe']='';
            $str['conclude']='';
        }
        $str['describe']=rtrim($str['describe'],'；');
        $str['describe'].='。';
        $str['conclude']=rtrim($str['conclude'],'；');
        $str['conclude'].='。';

        $this->describe_fob=$str['describe'];
        $this->conclude_fob=$str['conclude'];
    }

}